<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="司机姓名" prop="driverName" label-width="100px">
        <el-input
          v-model="queryParams.driverName"
          placeholder="请输入司机姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="司机联系电话" prop="driverPhone" label-width="100px">
        <el-input
          v-model="queryParams.driverPhone"
          placeholder="请输入司机联系电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="驾照号码" prop="licenseNo" label-width="100px">
        <el-input
          v-model="queryParams.licenseNo"
          placeholder="请输入驾照号码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="驾龄" prop="drivingExperience" label-width="100px">
        <el-input
          v-model="queryParams.drivingExperience"
          placeholder="请输入驾龄"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="信息创建时间" prop="createTime" label-width="100px">
        <el-input
          v-model="queryParams.createTime"
          placeholder="请输入信息创建时间"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="信息更新时间" prop="updateTime" label-width="100px">
        <el-input
          v-model="queryParams.updateTime"
          placeholder="请输入信息更新时间"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="司机状态" prop="status" label-width="100px">
        <el-select
          v-model="queryParams.status"
          clearable
          placeholder="请选择"
          style="width: 240px"
        >
          <el-option
            v-for="item in love_driver_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <div style="display: flex; justify-content: flex-end;">
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['driver:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['driver:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="司机信息ID" align="center" prop="driverId" />
      <el-table-column label="司机姓名" align="center" prop="driverName" />
      <el-table-column label="司机联系电话" align="center" prop="driverPhone" />
      <el-table-column label="驾照类型：C1/C2等" align="center" prop="licenseType" />
      <el-table-column label="驾照号码" align="center" prop="licenseNo" />
      <el-table-column label="驾龄" align="center" prop="drivingExperience" />
      <el-table-column label="司机状态" align="center" prop="status" :formatter="formatStatus" />
      <el-table-column label="驾驶证图片" align="center" prop="licensePhotoUrl">
        <template #default="scope">
          <image-preview :src="scope.row.licensePhotoUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="行驶证图片" align="center" prop="vehicleLicensePhotoUrl">
        <template #default="scope">
          <image-preview :src="scope.row.vehicleLicensePhotoUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="信息创建时间" align="center" prop="createTime" />
      <el-table-column label="信息更新时间" align="center" prop="updateTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['driver:info:edit']">修改</el-button>
          <el-button link type="warning" icon="Refresh" @click="handleUpdateStatus(scope.row)" v-hasPermi="['driver:info:status']">审核</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改代驾司机信息档案对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="infoRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="司机姓名" prop="driverName">
          <el-input v-model="form.driverName" placeholder="请输入司机姓名" />
        </el-form-item>
        <el-form-item label="司机联系电话" prop="driverPhone" label-width="110px">
          <el-input v-model="form.driverPhone" placeholder="请输入司机联系电话" />
        </el-form-item>
        <el-form-item label="驾照号码" prop="licenseNo" label-width="110px">
          <el-input v-model="form.licenseNo" placeholder="请输入驾照号码" />
        </el-form-item>
        <el-form-item label="驾龄" prop="drivingExperience" label-width="110px">
          <el-input v-model="form.drivingExperience" placeholder="请输入驾龄" />
        </el-form-item>
        <el-form-item label="司机状态" prop="status" label-width="110px">
          <el-radio-group v-model="form.status">
          <el-radio 
            v-for="item in love_driver_status" 
            :key="item.value" 
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
        </el-form-item>
        <el-form-item label="驾照类型" prop="licenseType" label-width="110px">
        <el-select v-model="form.licenseType" placeholder="请选择驾照类型">
            <el-option
              v-for="item in licenseTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增：修改司机状态对话框 -->
    <el-dialog title="修改司机状态" v-model="statusDialogVisible" width="300px" append-to-body>
    <el-form :model="statusForm" label-width="100px">
      <el-form-item label="司机状态" prop="newStatus">  
        <el-select 
          v-model="statusForm.newStatus" 
          placeholder="请选择状态" 
          clearable>
          <el-option label="未注册" value="1"></el-option>
          <el-option label="可用" value="2"></el-option>
          <el-option label="休息" value="3"></el-option>
          <el-option label="冻结" value="4"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="statusDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmUpdateStatus">确认修改</el-button>
    </template>
  </el-dialog>
  </div>
  
</template>

<script setup name="Info">
import { ref, reactive,nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { listInfo, getInfo, delInfo, addInfo, updateInfo,updateStatus  } from "@/api/driver/info"

const { proxy } = getCurrentInstance()
const {love_driver_status} = proxy.useDict('love_driver_status')

const infoList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const licenseTypeOptions = ref([ // 直接用 ref 定义
  { label: 'A1大型客车', value: 'A1' },
    { label: 'A2牵引车', value: 'A2' },
    { label: 'A3城市公交车', value: 'A3' },
    { label: 'B1中型客车', value: 'B1' },
    { label: 'B2大型货车', value: 'B2' },
    { label: 'C1小型汽车', value: 'C1' },
    { label: 'C2小型自动挡汽车', value: 'C2' },
    { label: 'C3低速载货汽车', value: 'C3' },
    { label: 'C4三轮汽车', value: 'C4' },
    { label: 'C5残疾人专用小型自动挡载客汽车', value: 'C5' },
    { label: 'C6轻型牵引挂车', value: 'C6' },
    { label: 'D普通三轮摩托车', value: 'D' },
    { label: 'E普通二轮摩托车', value: 'E' },
    { label: 'F轻便摩托车', value: 'F' },
    { label: 'M轮式自行机械车', value: 'M' },
    { label: 'N无轨电车', value: 'N' },
    { label: 'P有轨电车', value: 'P' }
])

// 状态映射函数
const formatStatus = (row) => {
  const statusMap = {
    1: '未注册',
    2: '可用',
    3: '休息',
    3: '冻结'
  };
  return statusMap[row.status] || '未知'; // 兜底防止异常值
};
// 新增：修改状态弹窗相关数据
const statusDialogVisible = ref(false);
const statusForm = reactive({
  newStatus: '', // 存储选择的新状态
  driverId: ''   // 存储当前要修改状态的司机 ID
});
// 点击“修改状态”按钮时触发，打开弹窗并赋值当前司机信息
const handleUpdateStatus = (row) => {
  // 1. 先打开弹窗，让 el-form-item 完成初始化
  statusDialogVisible.value = true;
  // 2. 用 nextTick 确保弹窗和表单已渲染，再赋值
  nextTick(() => {
    statusForm.driverId = row.driverId;
    statusForm.newStatus = row.status; // 此时 el-form-item 已初始化，能捕获到值
  });
};
// 确认修改状态，调用新增的 updateStatus 接口
async function confirmUpdateStatus() {
  const updateData = {
    driverId: statusForm.driverId,
    status: statusForm.newStatus 
  };
  updateStatus(updateData).then(response => {
    ElMessage.success('司机状态修改成功');
    statusDialogVisible.value = false;
    getList();
  }).catch(error => {
    ElMessage.error('状态修改失败，请重试');
  });
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    driverName: null,
    driverPhone: null,
    licenseType: null,
    licenseNo: null,
    drivingExperience: null,
    status: null,
    licensePhotoUrl: null,
    vehicleLicensePhotoUrl: null,
    createTime: null,
    updateTime: null
  },
  rules: {
    driverName: [
      { 
        pattern: /^[\u4e00-\u9fa5a-zA-Z]{2,20}$/, 
        message: '司机姓名需为2-20个中文或字母', 
        trigger: 'blur' 
      },
      { 
        required: true, 
        message: '请输入司机姓名', 
        trigger: 'blur' 
      }
    ],
    driverPhone: [
      { 
        pattern: /^1[3-9]\d{9}$/, 
        message: '请输入正确的11位手机号码', 
        trigger: 'blur' 
      },
      { 
        required: true, 
        message: '请输入司机联系电话', 
        trigger: 'blur' 
      }
    ],
    licenseType: [
      { required: true, message: '请选择驾照类型', trigger: 'change' }
    ],
    drivingExperience: [
      { 
        pattern: /^([1-9]|[1-4]\d|50)$/, // 正则表达式，匹配 1-50 的数字
        message: '驾龄只能输入 1 到 50 之间的数字', 
        trigger: 'blur' 
      },
      { 
        required: true, 
        message: '请输入司机驾龄', 
        trigger: 'blur' 
      }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询代驾司机信息档案列表. */
function getList() {
  loading.value = true
  listInfo(queryParams.value).then(response => {
    infoList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    driverId: null,
    driverName: null,
    driverPhone: null,
    licenseType: null,
    licenseNo: null,
    drivingExperience: null,
    status: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("infoRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.driverId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加代驾司机信息档案"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _driverId = row.driverId || ids.value
  getInfo(_driverId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改代驾司机信息档案"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["infoRef"].validate(valid => {
    if (valid) {
      if (form.value.driverId != null) {
        updateInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _driverIds = row.driverId || ids.value
  proxy.$modal.confirm('是否确认删除代驾司机信息档案编号为"' + _driverIds + '"的数据项？').then(function() {
    return delInfo(_driverIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('driver/info/export', {
    ...queryParams.value
  }, `info_${new Date().getTime()}.xlsx`)
}

getList()
</script>
